<template>
<view class="page2 profile">
    <form @submit="submit" class="form">
        <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <image class="avatar" :src="info.avatarUrl"></image>
        </button>
        <nut-input 
            v-model="form.nickName" 
            label="昵称" 
            placeholder="请输入您的昵称" 
            type="nickname"
        />
        <nut-button type="info" class="submit" form-type="submit">保存信息</nut-button>
    </form>
</view>
</template>

<script>
import { ref, reactive, onBeforeMount } from 'vue';
import { useUserStore, useConfigStore } from '@/stores'
import { storeToRefs } from 'pinia';
import { setStorageSync, showToast, showLoading, hideLoading } from '@tarojs/taro'
import { switchTab } from '@/router'
import { QiniuToken, updateProfile } from "@/api/index";
import "./index.scss";

export default{
    setup(){
        definePageConfig({
            navigationBarTitleText: '个人资料'
        })
        const user = useUserStore()
        const config = useConfigStore()
        const { info } = storeToRefs(user);
        const oldForm = {
            nickName: info.value.nickName,
            avatarUrl: info.value.avatarUrl
        }
        const form = reactive({...oldForm}) // form深拷贝
        const avatar = ref('');
        let formData = {'token': '', 'x:type': 15};
        let chooseImgFlag = false; 
        onBeforeMount(() => {
            QiniuToken({file_type:'img'}).then((res) => {
                if(res&&res.data){
                    formData.token = res.data.qiniuToken
                }
            })
        })
        function compareForm() {
            const arr = Object.keys(oldForm)
            let parame = {}
            for (let item of arr) {
                if (form[item] !== oldForm[item]) {
                    parame[item] = form[item]
                }
            }
            return Object.keys(parame).length
        }
        function updateInfo(mini_avatar){
            const parame = {mini_avatar, mini_nickname: form.nickName}
            updateProfile(parame).then(()=>{
                form.avatarUrl = mini_avatar
                setStorageSync('info', form)
                user.setUserInfo(form)
                showToast({title: '更新成功',icon: 'success', duration: 2000})
                setTimeout(()=> switchTab({url: '/pages/ucenter/index'}), 2000)
            })
        }
        function submit(){
            if(compareForm()===0){
                return showToast({title: '您没有进行任何修改', icon: 'none'})
            }
            if(!chooseImgFlag){  // 没选择头像只更新昵称
                return updateInfo(form.avatarUrl)
            }
            if(avatar.value){  // 头像已经上传过
                return updateInfo(avatar.value)
            }
            showLoading({title: '加载中', mask: true});
            wx.uploadFile({
                url: config.oemInfo.qiniu_url,
                filePath: form.avatarUrl,
                name: 'file',
                formData,
                success: (res) => {
                    const trans = JSON.parse(res.data)
                    avatar.value = trans.data.path
                    updateInfo(avatar.value)
                },
                fail(){
                    showToast({ title: '头像上传失败', icon: 'none', duration: 3000})
                },
                complete: hideLoading,
            })
        }
        function onChooseAvatar(e) {
            chooseImgFlag = true
            const { avatarUrl } = e.detail 
            form.avatarUrl = avatarUrl
            user.setUserInfo({ avatarUrl })
        }
        return {
            form,
            info,
            submit,
            onChooseAvatar,
        }
    },
}
</script>
